package com.dog.basics.mqtt.send;

import com.dog.basics.mqtt.config.MqttConfig;
import org.springframework.context.annotation.Lazy;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @description: 消息发送
 * @author: He
 * @date: Created in 2020/9/29 12:14
 * @version: 1.0
 * @modified By:
 */
@Component
public class IMqttSender {

    @Lazy
    @Resource(name = MqttConfig.CHANNEL_NAME_OUT)
    private MessageChannel messageChannel;

    /**
     * 发送信息到MQTT服务器
     *
     * @param topic   主题
     * @param payload 消息主体
     */
   public Boolean sendToMqtt(@Header(MqttHeaders.TOPIC) String topic,
                       String payload) {
        Message<String> build = MessageBuilder
                .withPayload(payload)
                .setHeader(MqttHeaders.TOPIC, topic)
                .build();
        return messageChannel.send(build);
    }

    /**
     * 发送信息到MQTT服务器
     *
     * @param topic   主题
     * @param qos     对消息处理的几种机制。<br> 0 表示的是订阅者没收到消息不会再次发送，消息会丢失。<br>
     *                1 表示的是会尝试重试，一直到接收到消息，但这种情况可能导致订阅者收到多次重复消息。<br>
     *                2 多了一次去重的动作，确保订阅者收到的消息有一次。
     * @param payload 消息主体
     */
    public Boolean sendToMqtt(String topic, int qos, String payload) {
        Message<String> build = MessageBuilder
                .withPayload(payload)
                .setHeader(MqttHeaders.TOPIC, topic)
                .setHeader(MqttHeaders.QOS, qos)
                .build();
        return messageChannel.send(build);
    }

}
